package com.atguigu.gmall.all.controller;

import com.alibaba.fastjson.JSONObject;
import com.atguigu.gmall.common.result.Result;
import com.atguigu.gmall.model.product.BaseCategoryView;
import com.atguigu.gmall.product.client.ProductFeignClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;

import javax.jws.WebParam;
import java.io.*;
import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @Author: 李旭
 * @Time: 9:37
 * @Description:
 * 首页
 *
 */
@Controller
public class IndexController {


    @Autowired
    private ProductFeignClient productFeignClient;
    //http://www.gmall.com
    @GetMapping("/")
    public String index(Model model){
        List<Map> result = buildData();
        model.addAttribute("list",result);
        return "index/index";
    }

    //使用静态化技术生成页面  Win10 D:\temp\index.html   ==   Linux  /usr/local/html/index.html
    @Autowired
    private TemplateEngine templateEngine;//模板引擎
    //生成静态化页面  半夜12点   人为手动触发   定时器
    @GetMapping("/createHtml")
    @ResponseBody
    public Result createHtml(){
        //重点： 使用静态化技术生成页面
        //thymeleaf : 页面标签  <div th:text  th:if th:each
        //静态化技术 ： 将有标签页面 模板 .html + 数据 =渲染= 输出（无标签页面  静态化后的页面.html）
        //数据
        Context context = new Context();
        context.setVariable("list",buildData());
        //输出流
        Writer writer = null;
        try {
            //乱码 问题
            //读：utf-8
            //写: utf-8
/*            writer = new OutputStreamWriter(
                    new FileOutputStream("D:\\temp\\index.html"),"utf-8");*/
            writer = new PrintWriter("D:\\temp\\index.html","utf-8");
            //=渲染=
            templateEngine.process("index/index",context,writer);//处理==渲染
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            try {
                if(writer != null)
                    writer.close();//空指针异常
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return Result.ok();
    }

    //构建数据
    public List<Map> buildData(){
        //三级分类视图集合
        List<BaseCategoryView> baseCategoryViewList =
                productFeignClient.getBaseCategoryViewList();
        //Stream流
        //Long : K  一级分类ID  分组字段  1   2  3
        //List<BaseCategoryView> : 分组后集合  60  25  。。
        Map<Long, List<BaseCategoryView>> baseCategoryViewListGroup = baseCategoryViewList
                .stream().collect(Collectors.groupingBy(BaseCategoryView::getCategory1Id));
        //办法一：
        //POJO
        // categoryId
        // categoryName
        // List<POJO> categoryChild
        //办法二：  文档上使用是此种方法  难的代码
        //无敌POJO  Map
        // map.put(categoryId,V);
        // map.put(categoryName,V);
        // map.put(categoryChild,List<>);

        //最终结果集合
        List<Map> result = new ArrayList<>();
        //行号
        int index = 1;
        for (Map.Entry<Long, List<BaseCategoryView>> category1Entry :
                baseCategoryViewListGroup.entrySet()) {
            // category1Entry.getKey()//一级分类ID
            // category1Entry.getValue()// 一级分类ID对应的集合
            Map category1Map = new HashMap();
            category1Map.put("index",index++);
            category1Map.put("categoryId",category1Entry.getKey());
            List<BaseCategoryView> category1List = category1Entry.getValue();
            category1Map.put("categoryName", category1List.get(0).getCategory1Name());
            //======================================================
            //二级分类集合
            List<Map> category2ListMap = new ArrayList<>();
            Map<Long, List<BaseCategoryView>> category2ListGroup = category1List.stream().collect(Collectors.groupingBy(
                    BaseCategoryView::getCategory2Id));
            for (Map.Entry<Long, List<BaseCategoryView>> category2Entry :
                    category2ListGroup.entrySet()) {
                Map category2Map = new HashMap();
                category2Map.put("categoryId",category2Entry.getKey());
                List<BaseCategoryView> category2List = category2Entry.getValue();
                category2Map.put("categoryName", category2List.get(0).getCategory2Name());
                //======================================================
                //三级分类集合
                List<Map> category3ListMap = new ArrayList<>();
                for (BaseCategoryView baseCategoryView : category2List) {
                    Map category3Map = new HashMap();
                    category3Map.put("categoryId",baseCategoryView.getCategory3Id());
                    category3Map.put("categoryName", baseCategoryView.getCategory3Name());
                    category3ListMap.add(category3Map);
                }
                //======================================================
                category2Map.put("categoryChild",category3ListMap);
                category2ListMap.add(category2Map);
            }
            //======================================================
            category1Map.put("categoryChild",category2ListMap);
            result.add(category1Map);
        }
        return result;
    }
}
